/*
 * EZCP_Sim_Send.c
 *
 *  Created on: Apr 18, 2011
 *      Author: Nidhanee
 */

#include "EZCP_Sim_Common.h"
extern unsigned int MSG_DATA_LENGTHS [EZCP_NUM_OF_MSGS];

void EZCP_Simu_ConnectToChannel( s32 *si_server_coid )
{
	if (-1 == (*si_server_coid = name_open(EZCP_ATTACH_SIMU2APP, 0)))
	{
		err(-1,"%s: name_open error",__func__);
	}
}

void *pf_Sender()
{
    s32 si_server_coid = 0;
	EZCP_Simu_ConnectToChannel(&si_server_coid);

	EZCP_Simu_ReadIncomingMsg (si_server_coid);

    /* Close the connection */
    name_close(si_server_coid);

	return NULL;
}


/*Read message from File and send it across the channel to App */
void EZCP_Simu_ReadIncomingMsg (s32 si_server_coid)
{
	FILE * fp_SimData;
	char lineBuf [EZCP_SIM_DATA_LINE_LEN + 1], *ptr_tok, *ptr_sp;
	msg_data_buf_t buf_data;
	u32 ui_msDelay, ui_dataCnt, ui_temp;
	u8  msgID;

	fp_SimData = fopen (SIMDATA_FILE_NAME, "r");
	if (NULL == fp_SimData)
	{
		err (-1,"Simulation data file [%s] can not be opened.", SIMDATA_FILE_NAME);
	}

	//Read each line from file
	while (NULL != (fgets (lineBuf, EZCP_SIM_DATA_LINE_LEN, fp_SimData)))
	{
		//printf ("%s: Sim-data line [%s]\n",__func__,lineBuf);

		//Each Line contains:
		//<millisec>|<msg-id>|<byte1>|<byte2>|....

		//Read First token: 'delay time' (milliseconds) ... decimal number
		ptr_tok = strtok_r (lineBuf, "|", &ptr_sp); //First call to strtok_r
		sscanf (ptr_tok, "%d", &ui_msDelay);

		//Read next token: 'message ID' ... hex number
		ptr_tok = strtok_r (NULL, "|", &ptr_sp);
		sscanf (ptr_tok, "%d", &ui_temp);
		//printf ("%s: ui_temp = %d\n",__func__,ui_temp);
		msgID = ui_temp;
		//print ("%s: msgID = %d\n",__func__,msgID);

		//print("%s: buf_data = ",__func__);
		//Read next tokens: data byte(s) ... hex number
		ui_dataCnt = 0;
		ptr_tok = strtok_r (NULL, "|", &ptr_sp);
		while (NULL != ptr_tok)
		{
			sscanf (ptr_tok, "%x", &ui_temp);
			buf_data[ui_dataCnt] = ui_temp;
			//print("%x|",buf_data[ui_dataCnt]);
			ui_dataCnt++;
			ptr_tok = strtok_r (NULL, "|", &ptr_sp);
		}
		//print("\n");
		delay (ui_msDelay);
		EZCP_Simu_SendIncomingMsg (si_server_coid, msgID, buf_data);
	}

	fclose (fp_SimData);
	return;
}

void EZCP_Simu_SendIncomingMsg (s32 si_server_coid, u8 ui_msgid, msg_data_buf_t buf_data)
{
	msg_header_t st_hdr;
	msg_buf_t buf_msg;
	u32 ui_hdr_len, ui_data_len, ui_msg_len;

    ui_hdr_len  = EZCP_HDR_LEN;
    ui_data_len = MSG_DATA_LENGTHS [ui_msgid - 1];
    ui_msg_len  = ui_hdr_len + ui_data_len;

    st_hdr.type    = ui_msgid;
    st_hdr.subtype = ui_data_len;
    memcpy (buf_msg, &st_hdr, ui_hdr_len);
    memcpy (buf_msg+ui_hdr_len, buf_data, ui_data_len);

    if (-1 == MsgSend(si_server_coid, buf_msg, ui_msg_len, NULL, 0))
    {
    	err (-1,"MsgSend ERROR");
    }
 }
